package com.school_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.school_admin.config.Result;
import com.school_admin.entity.Collection;
import com.school_admin.entity.Operation;
import com.school_admin.mapper.PostMapper;
import com.school_admin.service.impl.CollectionServiceImpl;
import com.school_admin.service.impl.OperationServiceImpl;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {
    private final PostMapper postMapper;
    private final OperationServiceImpl operationService;
    private final CollectionServiceImpl collectionService;

    public CollectionController(CollectionServiceImpl collectionService, PostMapper postMapper, OperationServiceImpl operationService) {
        this.collectionService = collectionService;
        this.postMapper = postMapper;
        this.operationService = operationService;
    }

    @PostMapping("createPostCollection")
    public Result<String> createPostCollection(Collection collection) {
        /*
             TODO 1. 获取前端传递的参数
             TODO 2. 判断用户是否已经收藏
             TODO 3. 调用service创建收藏记录
             TODO 4. 返回结果
         */
        LambdaQueryWrapper<Collection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collection::getUid, collection.getUid());
        Collection collectionOne = collectionService.getOne(wrapper);
        if (collectionOne != null) {
            return Result.fail("已经收藏过啦");
        } else {
            // 创建收藏记录
            boolean save = collectionService.save(collection);
            // 更新帖子收藏数量
            postMapper.updatePostCollectionCount(collection.getPostId());
            // 记录操作行为
//            Operation operation = new Operation();
//            operation.setType(1);
//            operation.setUid(collection.getUid());
//            operation.setPostId(collection.getPostId());
//            operationService.recordOperation(operation);
            // 返回结果
            if (save) {
                return Result.success("收藏成功");
            } else {
                return Result.fail("收藏失败");
            }
        }
    }
    // 移出收藏
    @DeleteMapping("removeCollection/{id}")
    public Result<String> removeCollection(@PathVariable int id) {
        boolean i = collectionService.removeById(id);
        return Result.success(i ? "移出收藏成功" : "移出收藏失败");
    }
}
